// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-02-11

package conf

import (
	"fmt"
	"regexp"
)

const (
	binlogDefaultTag = "__untag__"
)

var (
	binlogTagRegexp = regexp.MustCompile(`^[.|$]([_a-zA-Z0-9]+)$`)
)

// ErpBinlog
// 转发Binlog数据规则.
type ErpBinlog struct {
	// Topic
	// 主题名, 消息发到哪个主题下.
	Topic string `yaml:"topic"`

	// Tag
	// 标签名, 消息标签属性, 接受固定值或变量.
	//
	// - 固定标签, 如 success, 表示所有消息都使用相同的标签，且值为 success.
	// - 变量格式: `$字段名` 或 `.字段名`, 表示消息标签取字段名为success的值.
	Tag string `yaml:"tag"`
}

func (o *ErpBinlog) GenerateTag(data map[string]any) (tag string) {
	// 1. 赋默认值.
	defer func() {
		if tag == "" {
			tag = binlogDefaultTag
		}
	}()

	// 2. 取字段值.
	if m := binlogTagRegexp.FindStringSubmatch(o.Tag); len(m) == 2 {
		if v, ok := data[m[1]]; ok {
			tag = fmt.Sprintf(`%v`, v)
		}
		return
	}

	// 3. 取固定值.
	tag = o.Tag
	return
}
